<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="customer-container">
    <div :class="{'mobile-el-form': showMobilePage}" class="customer-data">
      <div style="display:flex;align-items:center;margin-bottom:10px;">
        <div><Title title="库存信息" font-size="16px"/></div>
        <div style="flex:1;"/>
      </div>
      <div style="padding-left:12px;">
        <detailInfo
          :detail-data="detailData"
          :loading="infoLoading"
          :is-mobile="showMobilePage"
          @securityValConfirm="securityValConfirm"
          @defectiveConfirm="defectiveConfirm"
        />
      </div>
      <div class="data-container" >
        <div class="data-container-title">
          <Title font-size="16px" title="数据统计" />
          <div v-if="listCount" class="data-container-btn-right">
            <slot name="btn-group">
              <div class="btn-group">
                <span :class="active === 0 ? 'now active' : 'now'" @click="handleMonthClick(0)">本月</span>
                <span :class="active === 1 ? 'pre active' : 'pre'" @click="handleMonthClick(1)">上月</span>
              </div>
              <el-date-picker
                v-model="monthTime"
                :clearable="false"
                value-format="timestamp"
                size="small"
                type="month"
                style="width:120px"
                placeholder="指定月份"
                @change="handleChange"/>
            </slot>
          </div>
        </div>
        <dataDisplay :data-list="listCount" class="data-list" />
      </div>
      <comparisonTable
        v-if="showComparisonTable"
        :is-mobile="showMobilePage"
        :comparison-data="comparisonData"
        @showStockDetailDialog="showStockDetailDialog"
        @dataChange="queryComparisonData"/>
      <stockInSection :detail-data="detailData" :is-mobile="showMobilePage" />
      <stockOutSection :detail-data="detailData" :is-mobile="showMobilePage" />
      <defectiveLog ref="defectiveLogRef" :id="inventoryId" />
    </div>
    <inventoryDetail ref="inventoryDetailRef" :id="inventoryId" :comparison-range-date="comparisonRangeDate" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import Title from '@/components/Title';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import detailInfo from './module/detailInfo';
import comparisonTable from './module/comparisonTable';
import inventoryDetail from './module/inventoryDetail';
import stockInSection from './module/stockInSection';
import stockOutSection from './module/stockOutSection';
import defectiveLog from './module/defectiveLog';
import {
  getInventoryDetail,
  getInventoryStatistics,
  editInventorySecurity,
  editDefectiveStockOut,
  getComparisonData
} from '@/api/mengli';
import { hasRouteAuth } from '@/utils/permission';
import { standardFormat } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import setting from '@/assets/setting.png';
import icon1 from '@/assets/mengli/inventory/icon1.png';
import icon2 from '@/assets/dataDisplay/rmb.png';
import icon3 from '@/assets/mengli/inventory/icon3.png';
import icon4 from '@/assets/mengli/inventory/icon4.png';
import icon5 from '@/assets/mengli/inventory/icon5.png';

export default {
  components: {
    Title,
    detailInfo,
    EmptyPlaceholder,
    comparisonTable,
    inventoryDetail,
    stockInSection,
    stockOutSection,
    defectiveLog,
    dataDisplay
  },
  filters: {
    moneyFilter,
    standardFormat,
    filterNon(val) {
      return (val !== 0 && !val) ? '--' : val;
    },
    bigNumber: (num) => {
      let formatNum = Math.abs(num);
      const sign = Math.sign(num);
      // 参数为正数，返回+1；
      // 参数为负数，返回-1；
      // 参数为 0，返回0；
      // 参数为-0，返回-0;
      // 其他值，返回NaN。
      if (formatNum) {
        if (formatNum >= 1000000000000) {
          formatNum = (formatNum / 1000000000000).toFixed(2) + '万亿';
        } else if (formatNum >= 100000000) {
          formatNum = (formatNum / 100000000).toFixed(2) + '亿';
        } else if (formatNum >= 10000) {
          formatNum = (formatNum / 10000).toFixed(2) + '万';
        }
        return sign === -1 ? `-${formatNum}` : formatNum;
      } else {
        return num;
      }
    }
  },
  data() {
    return {
      setting,
      inventoryId: '',
      detailData: {},
      comparisonData: {
        list: [],
        deadline: ''
      },
      monthTime: this.getCurrentMonth().getTime(),
      active: 0,
      statistics: null,
      infoLoading: false,
      cacheMonthTime: null,
      comparisonRangeDate: null
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    listCount() {
      const statisticsList = [{
        label: '入库数量',
        icon: icon1,
        data: this.statistics ? this.statistics['inventoryCount'] : '',
        isMoney: false
      }, {
        label: '入库总成本',
        icon: icon2,
        data: this.statistics ? this.statistics['inventoryTotalCost'] : ''
      }, {
        label: '出库数量',
        icon: icon3,
        data: this.statistics ? this.statistics['deliveryCount'] : '',
        isMoney: false
      }, {
        label: '出库总成本',
        icon: icon5,
        data: this.statistics ? this.statistics['deliveryTotalCost'] : ''
      }];
      if (this.detailData && this.detailData.repository && this.detailData.repository.type === 1) { // 加权平均类型仓库
        const costPriceData = {
          label: '成本价',
          icon: icon4,
          data: this.statistics ? this.statistics['costPrice'] : ''
        };
        statisticsList.splice(3, 0, costPriceData);
      }
      return statisticsList;
    },
    showComparisonTable() {
      // 数据对比功能只在仓库为：能源仓（淘宝订单关联的仓库）时显示
      return this.detailData.repository && this.detailData.repository.repositoryName === '能源仓';
    },
    rangeKeyArr() {
      return [{
        attr: 'dateRange',
        start: 'startTime',
        end: 'endTime',
        type: 'time'
      }];
    }
  },
  created() {
    this.inventoryId = Number(this.$route.params.id) || '';
    this.getData();
    this.handleMonthClick(0);
  },
  methods: {
    queryComparisonData(date) {
      this.comparisonRangeDate = date;
      const params = {};
      params.id = this.inventoryId;
      if (date) {
        params.dateRange = date;
        paramsRangeFormat(this.rangeKeyArr, params);
      }
      getComparisonData(params).then(res => {
        const list = [{ name: '共创平台' }, { name: '第三方库存' }, { name: '差值' }];
        Object.assign(list[0], res.data.gcInfo);
        Object.assign(list[1], res.data.thirdPartyInfo);
        Object.assign(list[2], res.data.differenceInfo);
        this.comparisonData.deadline = res.data.deadline.replace(/-/g, '/');
        this.comparisonData.list = list;
      });
    },
    setValue(data) {
      this.listCount.map(item => {
        item.value = data[item.label];
      });
    },
    getCurrentMonth() {
      const now = new Date();
      now.setDate(1);
      now.setHours(0);
      now.setSeconds(0);
      now.setMinutes(0);
      return now;
    },
    handleMonthClick(val) {
      const now = this.getCurrentMonth();
      this.active = val;
      this.monthTime = new Date(now.setMonth(now.getMonth() - val)).getTime();
      this.getListCount(this.monthTime);
    },
    handleChange() {
      this.active = 2;
      this.getListCount(this.monthTime);
    },
    getListCount(val) {
      this.cacheMonthTime = val;
      const params = {
        monthTime: val,
        inventoryId: this.inventoryId
      };
      getInventoryStatistics(params).then(res => {
        if (res.code === 200) {
          // this.setValue(res.data);
          this.statistics = res.data;
        }
      }).catch(err => {
        console.log(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    hasRouteAuth,
    getData() {
      this.infoLoading = true;
      getInventoryDetail(this.inventoryId).then(res => {
        this.infoLoading = false;
        if (res.code === 200) {
          this.detailData = res.data;
        }
      }).catch(err => {
        this.infoLoading = false;
        console.log(err);
      });
    },
    // 安全值
    securityValConfirm(val) {
      const params = {
        id: this.inventoryId,
        value: val
      };
      editInventorySecurity(params).then(_ => {
        this.$message.success('操作成功');
        this.getData();
      });
    },
    // 残次品出库
    defectiveConfirm(data) {
      const params = {
        id: this.inventoryId,
        value: data.value,
        type: data.type
      };
      editDefectiveStockOut(params).then(_ => {
        this.$message.success('操作成功');
        this.getData();
        this.$refs['defectiveLogRef'].queryOperateLogs();
      });
    },
    showStockDetailDialog(isStockIn) {
      this.$refs['inventoryDetailRef'].showDialog(isStockIn);
    }
  }
};
</script>

<style lang="scss" scoped>
.data-container-title {
  display: flex;
  align-items: center;
}
.data-list {
  margin: 10px 0 32px 0;
}
.customer-container {
  min-height: calc(100vh - 53px - 32px);
  margin: 16px;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  &.mobile-detail-wrap {
    margin: 0;
    padding: 20px 12px;
  }
}
.overdue-tag {
  margin-left: 8px;
  color: #FF504F;
  background-color: #fff;
  border: 1px solid #FF504F;
  width: 120px;
  height: 26px;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  i {
    margin-right: 5px;
    font-size: 16px;
  }
}
.edit-btn {
  width:80px;
  height:32px;
  background:rgba(64,110,255,1);
  border-radius:4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size:16px;
  font-family:PingFangSC-Medium,PingFang SC;
  color:#fff;
  line-height:32px;
  cursor: pointer;
  img {
    margin-left:5px;
    width: 15px;
    height: 15px;
  }
  &:hover {
    background: #2a58f0;
  }
}
.op-btn {
  color: #2a58f0;
  cursor: pointer;
}
.data-container-btn-right {
  display: flex;
  align-items: center;
}
.btn-group {
  width: 96px;
  height: 32px;
  padding: 5px 0 7px;
  border: 1px solid #DDD;
  opacity: 1;
  border-radius: 4px;
  margin-right: 16px;
  font-size: 0;
  background: #fff;
  span {
    font-size: 14px;
    display: inline-block;
    width: 46px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #666;
    cursor: pointer;
    &.active {
      color: #406EFF;
    }
  }
  .now {
    border-right: 1px solid  #DDD;
  }
}
</style>
